﻿using System.Security.Cryptography;
using System.Text;

namespace Xenta.Utils
{
    /// <summary>
    /// Represents the crypto utility.
    /// </summary>
    public static class CryptoUtility
    {
        /// <summary>
        /// Calculates the MD5 hash for the specified string.
        /// </summary>
        /// <param name="s">An input string.</param>
        /// <param name="enc">The encoding(if null, the Unicode encoding will be used).</param>
        /// <returns>The hash data.</returns>
        public static byte[] MD5Hash(string s, Encoding enc = null)
        {
            if(enc == null)
                enc = Encoding.Unicode;
            var inBuf = enc.GetBytes(s);
            byte[] outBuf = null;

            using(var alg = MD5.Create())
                outBuf = alg.ComputeHash(inBuf);
            return outBuf;
        }

        /// <summary>
        /// Calculates the SHA1 hash for the specified string.
        /// </summary>
        /// <param name="s">An input string.</param>
        /// <param name="enc">The encoding(if null, the Unicode encoding will be used).</param>
        /// <returns>The hash data.</returns>
        public static byte[] SHA1Hash(string s, Encoding enc = null)
        {
            if(enc == null)
                enc = Encoding.Unicode;
            var inBuf = enc.GetBytes(s);
            byte[] outBuf = null;

            using(var alg = new SHA1CryptoServiceProvider())
                outBuf = alg.ComputeHash(inBuf);
            return outBuf;
        }

        /// <summary>
        /// Calculates the HMAC-MD5 hash for the specified key and value.
        /// </summary>
        /// <param name="key">The key string.</param>
        /// <param name="value">The value string.</param>
        /// <param name="enc">The encoding(if null, the Unicode encoding will be used).</param>
        /// <returns>The hash data.</returns>
        public static byte[] HMACMD5Hash(string key, string value, Encoding enc = null)
        {
            if(enc == null)
                enc = Encoding.Unicode;
            var keyBuf = enc.GetBytes(key);
            var valBuf = enc.GetBytes(value);
            byte[] outBuf = null;

            using(var alg = new HMACMD5(keyBuf))
                outBuf = alg.ComputeHash(valBuf);
            return outBuf;
        }
    }
}
